package com.design;

import java.util.ArrayList;
import java.util.List;

/**
 * 渠道（观察者）
 */
public class ChannelSubject {
    private String channelName;
    private List<Subscriber> list=new ArrayList<>();

    public ChannelSubject(String channelName) {
        this.channelName = channelName;
    }
    /**
     * 订阅消息
     */
    public void subscribe(Subscriber subscriber){
        list.add(subscriber);
        System.out.println("【"+channelName+"】新订阅者加入。。。");
    }
     /**
      * 取消订阅消息
      */
     public void unsubscribe(Subscriber subscriber){
        list.remove(subscriber);
        System.out.println("【"+channelName+"】订阅者退出。。。");
     }
      /**
       * 发布消息
       */
      public void publish(String message){
        System.out.println("【"+channelName+"】发布消息："+message);
        for (Subscriber subscriber : list) {
            subscriber.onMessage(channelName, message);
        }
      }
       /**
        * 获取订阅者数量
        */
      public int getSubscriberCount(){
        return list.size();
      }
}
